package com.woolink.per.sys.user.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;

import com.woolink.per.log.syslog.RunLog;
import com.woolink.per.sys.authority.dao.AuthorityDao;
import com.woolink.per.sys.authority.pojo.Authority;
import com.woolink.per.sys.user.dao.UserDao;
import com.woolink.per.sys.user.pojo.User;

/**
 	* A data access object (DAO) providing persistence and search support for User entities.
 			* Transaction control of the save(), update() and delete() operations 
		can directly support Spring container-managed transactions or they can be augmented	to handle user-managed Spring transactions. 
		Each of these methods provides additional information for how to configure it for the desired type of transaction control. 	
	 * @see com.wootide.ets.sys.user.pojo.User
  * @author MyEclipse Persistence Tools 
 */

public class UserDaoImpl extends HibernateDaoSupport implements UserDao
{
    private static final Logger log = LoggerFactory.getLogger(UserDaoImpl.class);
    
    private RunLog runLog;
    
    private AuthorityDao authorityDao;
    
    public List<GrantedAuthority> loadUserAuthoritiesByName(String username) 
    {
        try {

            List<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();

            List<String> query = loadUserAuthorities(username);

            for (String roleName : query) {
                GrantedAuthorityImpl authority = new GrantedAuthorityImpl(
                        roleName);
                auths.add(authority);
            }
            return auths;

        } catch (RuntimeException re) {
            log.error("find by authorities by username failed.", re);
            throw re;
        }
    }
    
    /**
     * 根据用户账号返回SysUsers实例对象。
     * 
     * @author sparta 2011-4-8 下午01:53:05
     *@param userAccount
     *            用户账号，比如admin等。
     *@return SysUsers实例对象。
     */
    public User findByUserName(String userName) {
        log.debug("根据userName查找User实例对象: " + userName);
        try {
            User instance = (User) getHibernateTemplate().find(
                    "from User where user_name='" + userName + "'")
                    .get(0);
            if (instance == null) {
                log.debug("没有相匹配的User实例对象！");
                instance = new User();
            } else {
                log.debug("相匹配的User实例对象被找到！");
            }
            return instance;
        } catch (RuntimeException re) {
            log.error("findByUserName() 错误！", re);
            throw re;
        }
    }
    
    /**
     *@author sparta 2011-3-30 下午03:51:48
     *@param username
     *@param session
     *@return
     */
    public List<String> loadUserAuthorities(final String username) {
        try {
            return this.getHibernateTemplate().executeFind(
                    new HibernateCallback() {
                        public List<Authority> doInHibernate(
                                Session session) throws HibernateException,
                                SQLException {
                            Query query = session
                                    .createSQLQuery("select a.authority_name "
                                            + "from sys_authority a, sys_role_authority b, sys_user_role c, sys_user d "
                                            + "where   a.authority_id = b.authority_id and b.role_id = c.role_id  "
                                            + "and c.user_id = d.user_id and  d.user_name = '"
                                            + username + "'");
                            return query.list();
                        }
                    });

        } catch (RuntimeException re) {
            log.error("find by authorities by username failed.", re);
            throw re;
        }
    }
    
    
    public List<String> loadUserResourcesByAuth(String authName)
    {
        
        return authorityDao.findResourcesName(authName);
        
    }

    protected void initDao()
    {
        //do nothing
    }
    
    public void save(User transientInstance)
    {
        log.debug("saving User instance");
        try
        {
            getHibernateTemplate().save(transientInstance);
            log.debug("save successful");
        }
        catch (RuntimeException re)
        {
            log.error("save failed", re);
            throw re;
        }
    }
    
    public void delete(User persistentInstance)
    {
        log.debug("deleting User instance");
        try
        {
            getHibernateTemplate().delete(persistentInstance);
            log.debug("delete successful");
        }
        catch (RuntimeException re)
        {
            log.error("delete failed", re);
            throw re;
        }
    }
    
    public User findById(java.lang.Integer id)
    {
        log.debug("getting User instance with id: " + id);
        try
        {
            User instance = (User)getHibernateTemplate().get("com.wootide.ets.sys.User",
                    id);
            return instance;
        }
        catch (RuntimeException re)
        {
            log.error("get failed", re);
            throw re;
        }
    }
    
    public List findByExample(User instance)
    {
        log.debug("finding User instance by example");
        try
        {
            List results = getHibernateTemplate().findByExample(instance);
            log.debug("find by example successful, result size: "
                    + results.size());
            return results;
        }
        catch (RuntimeException re)
        {
            log.error("find by example failed", re);
            throw re;
        }
    }
    
    public List findByProperty(String propertyName, Object value)
    {
        log.debug("finding User instance with property: " + propertyName
                + ", value: " + value);
        try
        {
            String queryString = "from User as model where model."
                    + propertyName + "= ?";
            return getHibernateTemplate().find(queryString, value);
        }
        catch (RuntimeException re)
        {
            log.error("find by property name failed", re);
            throw re;
        }
    }
    
    public List findAll()
    {
        log.debug("finding all User instances");
        try
        {
            String queryString = "from User";
            return getHibernateTemplate().find(queryString);
        }
        catch (RuntimeException re)
        {
            log.error("find all failed", re);
            throw re;
        }
    }
    
    public User merge(User detachedInstance)
    {
        log.debug("merging User instance");
        try
        {
            User result = (User)getHibernateTemplate().merge(detachedInstance);
            log.debug("merge successful");
            return result;
        }
        catch (RuntimeException re)
        {
            log.error("merge failed", re);
            throw re;
        }
    }
    
    public void attachDirty(User instance)
    {
        log.debug("attaching dirty User instance");
        try
        {
            getHibernateTemplate().saveOrUpdate(instance);
            log.debug("attach successful");
        }
        catch (RuntimeException re)
        {
            log.error("attach failed", re);
            throw re;
        }
    }
    
    public void attachClean(User instance)
    {
        log.debug("attaching clean User instance");
        try
        {
            getHibernateTemplate().lock(instance, LockMode.NONE);
            log.debug("attach successful");
        }
        catch (RuntimeException re)
        {
            log.error("attach failed", re);
            throw re;
        }
    }
    
    public static UserDaoImpl getFromApplicationContext(ApplicationContext ctx)
    {
        return (UserDaoImpl)ctx.getBean("UserDAO");
    }

    /**
     * @return Returns the runLog.
     */
    public RunLog getRunLog()
    {
        return runLog;
    }

    /**
     * @param runLog The runLog to set.
     */
    public void setRunLog(RunLog runLog)
    {
        this.runLog = runLog;
    }

    /**
     * @return Returns the authorityDao.
     */
    public AuthorityDao getAuthorityDao()
    {
        return authorityDao;
    }

    /**
     * @param authorityDao The authorityDao to set.
     */
    public void setAuthorityDao(AuthorityDao authorityDao)
    {
        this.authorityDao = authorityDao;
    }
    
}